﻿//l_reply.cpp

#include "reply.hpp"
#include "l_reply.hpp"
#include "l_utility.hpp"
#include <iostream>

namespace http {
	namespace server3 {

		const char* l_reply_metatable = "l_reply_metatable";

        static int l_reply_pushHeader(lua_State* L){
            if(lua_gettop(L) != 2) return 0;
            reply * _reply = l_get_reply(L);
            if(_reply != NULL && lua_isstring(L,1) && lua_isstring(L,2)) {
                    _reply->add_header(luaL_checkstring(L, 1),luaL_checkstring(L, 2));
            }
            return 0;
        }

        /// call reply::append_header function
        /// append new header without knowing whether it has existed
        static int l_reply_appendHeader(lua_State* L){
            if(lua_gettop(L) != 2) return 0;
            reply * _reply = l_get_reply(L);
            if(_reply != NULL && lua_isstring(L,1) && lua_isstring(L,2)) {
                _reply->append_header(luaL_checkstring(L, 1),luaL_checkstring(L, 2));
            }
            return 0;
        }

        static int  l_reply_setContent(lua_State* L){
            reply *_reply = l_get_reply(L);
            if(_reply != NULL && lua_isstring(L,1)) {
                    _reply->content.append(luaL_checkstring(L, 1));
			}						
			return 0;
        }

        static Util_Table_SI reply_statusArr[] = {
            {"ok",200},
            {"created",201},
            {"accepted", 202},
            {"no_content",204},
            {"multiple_choices",300},
            {"moved_permanently",301},
            {"moved_temporarily",302},
            {"not_modified",304},
            {"bad_request",400},
            {"unauthorized",401},
            {"forbidden",403},
            {"not_found",404},
            {"internal_server_error",500},
            {"not_implemented",501},
            {"bad_gateway",502},
            {"service_unavailable",503},
            {NULL,0}
        };

        static int  l_reply_getStatus(lua_State* L){
            reply * _reply = l_get_reply(L);
			if(_reply != NULL){				
                lua_pushnumber(L, _reply->status);
				return 1;
			}			
			return 0;
		}
        static int l_reply_setStatus(lua_State* L){
            reply * _reply = l_get_reply(L);
            if(_reply != NULL && lua_isnumber(L,1)){
                _reply->status = (reply::status_type) luaL_checknumber(L, 1);
			}		
			return 0;
		}

        static luaL_reg regArr[] = {            
            {"pushHeader", l_reply_pushHeader},
            {"appendHeader", l_reply_appendHeader},
            {"setContent", l_reply_setContent},
            {"getStatus", l_reply_getStatus},
            {"setStatus", l_reply_setStatus},
            {NULL, NULL}
        };

		int l_register_reply(lua_State* L){
            luaL_register(L, "reply", regArr);
            l_register_table_SI(L, -1,reply_statusArr,"status_type");			
			return 1;
		}

	}
}
